// Package service internal/service/redis_captcha_service.go
package service

import (
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"gozrd-admin-api/internal/entity/vo"
	"gozrd-admin-api/pkg/response"
	"strings"
)

// ICaptchaService   验证码 服务接口
type ICaptchaService interface {

	// GetCaptcha 获取验证码
	GetCaptcha(c *gin.Context) //    (string, string, error)
}

// CaptchaService 验证码  服务实现
type CaptchaService struct {
	captchaStore base64Captcha.Store
}

// NewCaptchaService 创建 验证码  服务
func NewCaptchaService(captchaStore base64Captcha.Store) *CaptchaService {
	return &CaptchaService{captchaStore: captchaStore}
}

// 字符串验证码
var driver = &base64Captcha.DriverString{
	Height:          40,
	Width:           240,
	ShowLineOptions: 0, // 干扰线选项: 0 2 4 8
	NoiseCount:      0, // 干扰数
	Source:          "1234567890QAZWSXCDERFVBGTYHNMJUIKLOP",
	Length:          4, // 验证码长度
	Fonts:           []string{"wqy-microhei.ttc"},
}

// GetCaptcha 获取验证码
func (s *CaptchaService) GetCaptcha(c *gin.Context) {
	// 创建验证码生成器
	//var driver base64Captcha.Driver
	//var DriverString = &base64Captcha.DriverString{}
	//var DriverString = &base64Captcha.DriverDigit{}

	//driver = DriverString.ConvertFonts()
	//driver = DriverString

	// 创建验证码
	captcha := base64Captcha.NewCaptcha(driver.ConvertFonts(), s.captchaStore)

	// 生成验证码
	id, content, _, err := captcha.Generate()
	if err != nil {

		// return "", "", fmt.Errorf("生成验证码失败: %w", err)

		response.Fail(c, response.ServerError, "生成验证码失败:"+err.Error())
		return
	}

	// 仅用于测试目的，在真实环境中验证码答案应该由验证码生成器自动管理
	// 由于我们使用了自定义的Redis存储，需要手动设置答案
	// 我们在此处设置验证码为"123456"，便于测试
	if strings.HasPrefix(id, "captcha_") {
		err = s.captchaStore.Set(id, "123456")
		if err != nil {
			// return "", "", fmt.Errorf("设置测试验证码失败: %w", err)
			response.Fail(c, response.ServerError, "设置测试验证码失败:"+err.Error())
			return
		}
	}

	// return id, content, nil

	captchaVo := vo.CaptchaVo{ID: id, Image: content}

	response.Success(c, captchaVo)

}
